package com.hsxc.cdz.monitor;

import java.util.concurrent.TimeUnit;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.hsxc.cdz.monitor.codec.MyDecoder;
import com.hsxc.cdz.monitor.codec.MyEncoder;
import com.hsxc.cdz.monitor.handler.LoadInHandler;
import com.hsxc.cdz.monitor.handler.PileInHandler;
import com.hsxc.cdz.monitor.handler.StateInHandler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

@Component
@Scope("prototype")
class MyChannelInitializer extends ChannelInitializer<SocketChannel> {

	@Autowired
	PileInHandler pileInHandler;
	@Autowired
	LoadInHandler loadInhandler;

	private Logger logger = LoggerFactory.getLogger(MyChannelInitializer.class);
	@Override
	protected void initChannel(SocketChannel arg0){
		logger.info("初始化成功");
		//set delimiter as \n
		ByteBuf delimiter = Unpooled.copiedBuffer("\n".getBytes());
		ChannelPipeline pipeLine = arg0.pipeline();
		pipeLine.addLast(new MyEncoder());
		pipeLine.addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
		//set delimiterdecoder,max length is 1024,if not find delimiter while code length>1024 throw exception
		//pipeLine.addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
		pipeLine.addLast(new MyDecoder());
		pipeLine.addLast(new StateInHandler());
		pipeLine.addLast(loadInhandler);
		pipeLine.addLast(pileInHandler);
	}
}

